package fr.nghs.android.thport.gestures;

import org.libsdl.app.SDLActivity;

import android.view.MotionEvent;
import fr.nghs.android.common.MathUtils;
import fr.nghs.android.common.ScaleGestureDetector;
import fr.nghs.android.thport.THSurface;

/**
 * Move world map & rotate objects
 * Using 2 fingers rotation & movement
 * @author ng
 *
 */
public class WorldMoveAndObjectRotate
    implements ScaleGestureDetector.OnScaleGestureListener
{
    private static final float ANGLE_THRESH_FOR_RIGHT_CLICK = MathUtils.PI / 4f;
    
    private float prevX, prevY, angleSum;

    private THSurface surface;
    
    public WorldMoveAndObjectRotate(THSurface s)
    {
        surface = s;
    }
    
    @Override
    public boolean onScaleBegin(ScaleGestureDetector s)
    {
        prevX = Float.NaN;
        angleSum = 0f;
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector s)
    {
        boolean isFirst = Float.isNaN(prevX);
        prevX = s.getFocusX();
        prevY = s.getFocusY();

        if(isFirst)
        {
            surface.sendMouseEvent(MotionEvent.ACTION_DOWN, SDLActivity.MOUSE_BUTTON_MIDDLE, prevX, prevY, 1f);
        }
        else
        {
            final float c = s.getCurrentAngle();
            final float p = s.getPreviousAngle();
            angleSum += c - p;
        }
               
        surface.sendMouseEvent(MotionEvent.ACTION_MOVE, SDLActivity.MOUSE_BUTTON_MIDDLE, prevX, prevY, 1f);
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector s)
    {
        surface.sendMouseEvent(MotionEvent.ACTION_UP, SDLActivity.MOUSE_BUTTON_MIDDLE, prevX, prevY, 1f);
        
        // simulate right click on rotation
        if(MathUtils.abs(angleSum) >= ANGLE_THRESH_FOR_RIGHT_CLICK)
        {
            surface.sendMouseEvent(MotionEvent.ACTION_DOWN, SDLActivity.MOUSE_BUTTON_RIGHT, prevX, prevY, 1f);
            surface.sendMouseEvent(MotionEvent.ACTION_UP, SDLActivity.MOUSE_BUTTON_RIGHT, prevX, prevY, 1f);
        }
    }
}
